package com.kylin.common.util;

import java.util.*;
import javax.mail.*;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.ConnectionListener;
import javax.mail.event.TransportListener;
import javax.mail.internet.*;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;

import com.kylin.common.exception.BusinessException;
import com.kylin.common.exception.SystemException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class SendMailBean  implements  ConnectionListener {
	protected static Logger log = Logger.getLogger(SendMailBean.class);
	
	/** MIME閭欢瀵硅薄 */
    private Message newMessage; 
    /** 閭欢浼氳瘽瀵硅薄 */
    private Session sendMailSession;
    /** smtp鏄惁闇�瑕佽璇� */
    private boolean needAuth = true; 
    /** */
    private String username;
    private String password;
    private String fromAddress;
     private String charset = "UTF-8";
    private String contentType = "plain";;

    private Properties prop = new Properties();
    
    /**
     *
     */
    public SendMailBean() {
    	init();
     }

    private void init(){
        prop.put("mail.smtp.host", Config.getString("systemMail.smtpServer"));                 //锟斤拷锟斤拷SMTP锟斤拷锟�
        prop.put("mail.smtp.port", Config.getString("systemMail.smptPort","25"));
        prop.put("mail.smtp.auth", new java.lang.Boolean(needAuth).toString());
        this.username = Config.getString("systemMail.userName");
        this.password = Config.getString("systemMail.passWord");
        this.fromAddress = Config.getString("systemMail.mail");
        log.debug("smtp鏈嶅姟鍣細  = " + prop.get("mail.smtp.host"));
        log.debug("smtp绔彛  锛�  = " + prop.get("mail.smtp.port"));
    }
    
    public void setNeedAuth(boolean needAuth) {
    	 prop.put("mail.smtp.auth", new java.lang.Boolean(needAuth).toString());
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

 
    /**
     *  锟斤拷锟斤拷锟脚硷拷
     * @return
     * @throws BusinessException 
     */
    public void send( String p_to, String p_subject, String p_message) throws BusinessException {
        if (needAuth) {
            sendMailSession = Session.getInstance(prop, new AuthenticatorBean(username, password));
        } else {
            sendMailSession = Session.getInstance(prop, null);
        }    	 
        newMessage = new MimeMessage(sendMailSession);
        
        try {
			newMessage.setFrom(new InternetAddress(this.fromAddress));
            newMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(p_to));
			newMessage.setSubject(p_subject);
            Multipart mp = new MimeMultipart();
            MimeBodyPart mbp = new MimeBodyPart();            
            if (contentType.equals("text/html"))
                mbp.setContent("<meta http-equiv=Content-Type content=text/html; charset=" + this.charset + ">" + p_message, "text/html;charset=" + this.charset);
            else
                mbp.setText(p_message, charset);
            mp.addBodyPart(mbp);
            newMessage.setContent(mp);
		} catch (AddressException e) {
			throw new BusinessException(e);
		} catch (MessagingException e) {
			throw new BusinessException(e);
		} 
		send();

    }

 

    private void send() {
        if (sendMailSession == null || newMessage == null)
        	throw new SystemException("鏈垵濮嬪寲 閭欢鐩稿叧淇℃伅");
        Transport transport = null;
        try {
            transport = sendMailSession.getTransport("smtp");
            System.out.println("-----  Stratr ........");
            transport.addConnectionListener(this);
            transport.connect();
            transport.send(newMessage);
            transport.close();
            log.debug("绯荤粺閭欢閫氱煡鍙戦�佹垚鍔�:" + " 鐢� " + username  +" 鍙戦�佺粰 " + newMessage.getRecipients(Message.RecipientType.TO));
        } catch (MessagingException m) {
        	log.debug("绯荤粺閭欢閫氱煡鍙戦�佸け璐�: " + m);
        	throw new SystemException("绯荤粺閭欢閫氱煡鍙戦�佸け璐�: " + m);
        }finally{
            try {
                transport.close();
            } catch (Exception e) {
            }
        }
    }



    public static void main(String[] s) throws BusinessException, ConfigurationException, Exception {
    	String p_to = "nmlzh@163.com,test@test.com";
    	Config.load("E:\\workspace\\kylin\\WebRoot\\WEB-INF\\kylin-config.xml");
    	
 		String templetContent = FileOperater.getActivationMailFileContent("zh_CN");
 		int index = templetContent.indexOf("\n");
 		String subject = templetContent.substring(0,index);
 		String content = templetContent.substring(index,templetContent.length());
 		
 		// 鍦ㄦā鐗堟枃浠堕噷鐨勫彉閲忥紝妯＄増涓畾涔変负绫讳技锛� 娆㈣繋浣爗0}锛屼綘鐨勫瘑鐮佹槸 {1}
 		String[] paraValues= new String[]{
 			"aaaa",
 			"bbbb"
 		};
 		UTool.sendHtmlSystemMail(p_to, subject, content, paraValues );
    	
    	
    	
      	
System.out.println("-------------------over-----------");
    }


     class AuthenticatorBean extends Authenticator
    {

        private String m_username;
        private String m_userpass;

        public void setUsername(String username)
        {
            m_username = username;
        }

        public void setUserpass(String userpass)
        {
            m_userpass = userpass;
        }

        public AuthenticatorBean(String username, String userpass)
        {
            m_username = null;
            m_userpass = null;
            setUsername(username);
            setUserpass(userpass);
        }

        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(m_username, m_userpass);
        }
    }


	public void closed(ConnectionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void disconnected(ConnectionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void opened(ConnectionEvent arg0) {
		 System.out.println("start......opened");
		
	}


}